<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/12/19
 * Time: 14:46
 */

namespace app\api\controller;


use think\Db;

class Home extends Base
{
    private $user_id;
    private $page;
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    /**
     * 轮播
     * @return \think\response\Json
     * part   展示的位置   1 首页  2 经销商查询   3 试乘试驾   4 车辆网
     */
    public function banner(){
        header("Access-Control-Allow-Origin: *");
        $param = input('');
        $banner = Db::table('up_banner')
            ->field('banner_id, banner_title, banner_thumb, banner_type, banner_link, banner_cate, 
            banner_object_id')
            ->where('banner_part', $param['part'])
            ->where('banner_status', 1)
            ->order('banner_sort asc')
            ->select();
        if($banner){
            return json(['status' => 200, 'msg' => $banner]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 车系列表
     * @return \think\response\Json
     */
    public function carSeries(){
        header("Access-Control-Allow-Origin: *");
        $series = Db::table('up_car_series')->field('cs_id, cs_name')->select();
        if($series){
            return json(['status' => 200, 'msg' => $series]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 经销商列表
     * @return \think\response\Json
     * car_series   车系ID
     * dealer_name  经销商名称/城市名称
     * lat          纬度
     * lon          经度
     * sheng        省ID
     * shi          市ID
     * show_type    展示的位置   1 经销商地图展示   2 其他位置
     */
    public function dealer(){
        header("Access-Control-Allow-Origin: *");
        $param = input('');
        $where = [];
        if(isset($param['car_series']) && $param['car_series'] != ''){
            $where['dealer_car_id'] = $param['car_series'];
        }
        if(isset($param['sheng']) && $param['sheng'] != '' && isset($param['shi']) && $param['shi'] != ''){
            $where['dealer_sheng'] = $param['sheng'];
            $where['dealer_shi'] = $param['shi'];
        }
        if(isset($param['dealer_name']) && $param['dealer_name'] != ''){
            $where['dealer_name|district'] = ['like', '%' . $param['dealer_name'] . '%'];
        }
        $field = 'dealer_id, dealer_name, dealer_address, cs_name, dealer_phone, dealer_lon, dealer_lat,
        ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$param['lat'].'* PI() / 180 - dealer_lat * PI() / 180) / 2),2) + COS('.$param['lat'].' * PI() / 180) * COS(dealer_lat * PI() / 180) * POW(SIN(('.$param['lon'].' * PI() / 180 - dealer_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $order = 'distance asc';
        $dealer = Db::table('up_dealer')
            ->join('up_car_series', 'dealer_car_id = cs_id', 'left')
            ->join('up_area', 'district_id = dealer_shi', 'left')
            ->where($where)
            ->field($field)
            ->order($order);
        if($param['show_type'] != 1){
            $dealer->page($this->page, 10);
        }
        $dealer = $dealer->select();
        if($dealer){
            return json(['status' => 200, 'msg' => $dealer]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 试乘试驾
     * @return \think\response\Json
     * user_name     姓名
     * user_phone    手机号
     * sheng         省ID
     * shi           市ID
     * car_series_id 车系ID
     * dealer_id     经销商ID
     */
    public function drive(){
        header("Access-Control-Allow-Origin: *");
        $param = input('');
        $insert = [
            'try_user_id' => $this->user_id,
            'try_user_name' => $param['user_name'],
            'try_user_phone' => $param['user_phone'],
            'try_sheng' => $param['sheng'],
            'try_shi' => $param['shi'],
            'try_car_id' => $param['car_series_id'],
            'try_dealer_id' => $param['dealer_id'],
            'try_time' => $this->create_time
        ];
        $res = Db::table('up_drive')->insertGetId($insert);
        if($res){
            // 消息
            $dealer_name = Db::table('up_dealer')->where('dealer_id', $param['dealer_id'])->value('dealer_name');
            $car_name = Db::table('up_car_series')->where('cs_id', $param['car_series_id'])->value('cs_name');
            $title = '您已成功预约' . $dealer_name . $car_name . '试驾，稍后会有工作人员与您联系';
            $notice = [
                'notice_type' => 2,
                'notice_cate' => 3,
                'notice_subject_id' => $res,
                'notice_title' => $title,
                'notice_user' => ',0,' . $this->user_id . ',',
                'notice_read_user' => ',0,',
                'notice_del_user' => ',0,',
                'notice_time' => $this->create_time,
            ];
            Db::table('up_notice')->insert($notice);
            try{
                $send_user = (string)$this->user_id;
                $this->Jpush(1, $send_user, $title, ['send_type' => 7, 'try_id' => $res]);
            }catch(\Exception $e){
        
            }
            return json(['status' => 200, 'msg' => '提交成功']);
        }else{
            return json(['status' => 0, 'msg' => '提交失败']);
        }
    }
    
    /**
     * 查询记录
     * @return \think\response\Json
     */
    public function weiList(){
        $list = Db::table('up_wei')
            ->field('wei_id, wei_plate')
            ->where('wei_user_id', $this->user_id)
            ->order('wei_time desc')
            ->limit(9)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 违章记录详情
     * @return \think\response\Json
     * wei_id    违章ID
     */
    public function weiDetail(){
        $wei_id = input('wei_id');
        $info = Db::table('up_wei_info')
            ->field('wei_info_sheng, wei_info_action, wei_info_time, wei_info_price, wei_info_fen, 
            wei_info_punish, wei_info_other')
            ->where('wei_info_wei_id', $wei_id)
            ->select();
        if($info){
            return json(['status' => 200, 'msg' => $info]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 保存车辆违法记录
     * @return \think\response\Json
     * wei_plate   车牌号
     * wei_vin     车架号
     * wei_engine  发动机号
     * wei_info    违章记录
     *             wei_info_sheng    违章省份名称
     *             wei_info_action   违法行为
     *             wei_info_time     违法时间
     *             wei_info_price    处罚金额
     *             wei_info_fen      扣分
     *             wei_info_punish   行政处罚
     *             wei_info_other    其他措施
     */
    public function weiSave(){
        $wei_plate = trim(input('wei_plate'), ' '); // 车牌号
        $wei_vin = trim(input('wei_vin'), ' '); // 车架号
        $wei_engine = trim(input('wei_engine'), ' '); // 发动机号
        $wei_info = input('wei_info');
        $wei_info = json_decode($wei_info, true); // 违章记录
        
        $have = Db::table('up_wei')
            ->where('wei_plate', $wei_plate)
            ->where('wei_vin', ',' . $wei_vin)
            ->where('wei_engine', ',' . $wei_engine)
            ->find();
        $have_info = Db::table('up_wei_info')->where('wei_info_wei_id', $have['wei_id'])->find();
    
        if($have){ // 如果有记录
            Db::startTrans();
            try{
                // 更新保存时间
                Db::table('up_wei')->where('wei_id', $have['wei_id'])->update(['wei_time' => $this->create_time]);
                
                // 如果有保存过,删除之前的违章记录
                if($have_info){
                    Db::table('up_wei_info')->where('wei_info_wei_id', $have['wei_id'])->delete();
                }
                Db::commit();
                $wei_id = $have['wei_id'];
            }catch(\Exception $e){
                $wei_id = false;
                Db::rollback();
            }
        }else{ // 没有记录
            // 插入新记录
            $insert = [
                'wei_user_id' => $this->user_id,
                'wei_plate' => $wei_plate,
                'wei_vin' => $wei_vin,
                'wei_engine' => $wei_engine,
                'wei_time' => $this->create_time
            ];
            $wei_id = Db::table('up_wei')->insertGetId($insert);
        }
        if($wei_id){
            if(is_array($wei_info) && !empty($wei_info)){
                $all = [];
                foreach($wei_info as $k => $v){
                    $all[] = [
                        'wei_info_sheng' => $v['wei_info_sheng'], // 省名称
                        'wei_info_action' => $v['wei_info_action'], // 违法行为
                        'wei_info_time' => $v['wei_info_time'], // 违法时间
                        'wei_info_price' => $v['wei_info_price'], // 处罚金额
                        'wei_info_fen' => $v['wei_info_fen'], // 扣分
                        'wei_info_punish' => $v['wei_info_punish'], // 行政处罚
                        'wei_info_other' => $v['wei_info_other'], // 其他措施
                        'wei_info_wei_id' => $wei_id
                    ];
                }
                $res = Db::table('up_wei_info')->insert($all);
                if($res){
                    return json(['status' => 200, 'msg' => '保存成功']);
                }else{
                    return json(['status' => 0, 'msg' => '保存失败']);
                }
            }else{
                return json(['status' => 200, 'msg' => '保存成功']);
            }
        }else{
            return json(['status' => 0, 'msg' => '保存失败']);
        }
    }
    
    /**
     * 产品中心
     * @return \think\response\Json
     * page    页码
     */
    public function productCenter(){
        header("Access-Control-Allow-Origin: *");
        $carList = Db::table('up_car')
            ->join('up_car_cate', 'cc_id = car_cate_id', 'left')
            ->field('car_id, car_thumb, car_name, car_price, cc_name')
            ->where('car_del', 1)
            ->page($this->page, 10)
            ->order('car_time desc')
            ->select();
        if($carList){
            return json(['status' => 200, 'msg' => $carList]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 车辆详情
     * @return \think\response\Json
     * car_id    车辆ID
     */
    public function carDetail(){
        header("Access-Control-Allow-Origin: *");
        $car_id = input('car_id');
        $car = Db::table('up_car')
            ->join('up_car_cate', 'cc_id = car_cate_id', 'left')
            ->where('car_id', $car_id)
            ->field('car_id, car_thumb, car_images, car_name, car_price, car_news, cc_name, car_long_images')
            ->find();
        // 主图
        if($car['car_images']){
            $car['car_images'] = explode(',', trim($car['car_images'], ','));
        }else{
            $car['car_images'] = [];
        }
        // 车辆长图
        if($car['car_long_images']){
            $car['car_long_images'] = explode(',', trim($car['car_long_images'], ','));
        }else{
            $car['car_long_images'] = [];
        }
        // 参数
        $car_type = Db::table('up_car_type_param')
            ->join('up_car_type', 'c_type_id = ctp_type_id', 'left')
            ->where('ctp_car_id', $car_id)
            ->where('c_type_show', 1)
            ->field('ctp_type_id, c_type_name')
            ->group('ctp_type_id')
            ->select();
        if($car_type){
            foreach($car_type as $k => $v){
                $param_id = Db::table('up_car_type_param')
                    ->where('ctp_car_id', $car_id)
                    ->where('ctp_type_id', $v['ctp_type_id'])
                    ->column('ctp_param_id');
                $param_name = Db::table('up_car_param')
                    ->where('c_param_id', 'IN', $param_id)
                    ->where('c_param_show', 1)
                    ->column('c_param_name');
                $car_type[$k]['param_name'] = implode(',', $param_name);
            }
        }
        $car['param'] = $car_type;
        // 新闻资讯
        $new = Db::table('up_new')
            ->where('new_id', 'IN', $car['car_news'])
            ->where('new_status', 1)
            ->field('new_id, new_title, new_second_title, new_type, new_link')
            ->order('new_time desc')
            ->select();
        $car['news'] = $new;
        return json(['status' => 200, 'msg' => $car]);
    }
    
    /**
     * 车辆图集
     * @return \think\response\Json
     * car_id    车辆ID
     */
    public function carImages(){
        header("Access-Control-Allow-Origin: *");
        $car_id = input('car_id');
        $images = Db::table('up_car')
            ->where('car_id', $car_id)
            ->field('car_id, car_out_images, car_special_images, car_middle_images, car_chair_images, 
            car_detail_images, car_name')
            ->find();
        $images['car_out_images'] = explode(',', trim($images['car_out_images'], ','));
        $images['car_special_images'] = explode(',', trim($images['car_special_images'], ','));
        $images['car_middle_images'] = explode(',', trim($images['car_middle_images'], ','));
        $images['car_chair_images'] = explode(',', trim($images['car_chair_images'], ','));
        $images['car_detail_images'] = explode(',', trim($images['car_detail_images'], ','));
        return json(['status' => 200, 'msg' => $images]);
    }
    
    /**
     * 保修政策--年份
     * @return \think\response\Json
     */
    public function zhengCeYear(){
        $year = Db::table('up_zhengce')
            ->order('zc_year asc')
            ->field('zc_id, zc_year')
            ->where('zc_is_show', 1)
            ->select();
        return json(['status' => 200, 'msg' => $year]);
    }
    
    /**
     * 保修政策--标题
     * @return \think\response\Json
     * zc_id      政策ID
     */
    public function zhengCeTitle(){
        $zc_id = input('zc_id');
        $title = Db::table('up_zc_explain')
            ->where('explain_fid', $zc_id)
            ->field('explain_id, explain_name')
            ->select();
        return json(['status' => 200, 'msg' => $title]);
    }
    
    /**
     * 保修政策--内容
     * @return \think\response\Json
     * explain_id    说明ID
     */
    public function zhengCeContent(){
        $explain_id = input('explain_id');
        $content = Db::table('up_zc_explain')
            ->where('explain_id', $explain_id)
            ->field('explain_id, explain_content')
            ->select();
        return json(['status' => 200, 'msg' => $content]);
    }
    
    /**
     * 保修政策链接
     * @return \think\response\Json
     */
    public function zhengCeLink(){
        $link = Db::table('up_zhengce')->where('zc_id', 3)->value('zc_link');
        if($link){
            return json(['status' => 200, 'msg' => $link]);
        }else{
            return json(['status' => 200, 'msg' => '']);
        }
    }
    
    /**
     * 首页--活动 & 推荐购车 & 新闻
     * @return \think\response\Json
     */
    public function index(){
        $list = [];
        $list['activity'] = $this->activity(); // 活动（滚动字幕）
        $list['tuijian'] = $this->carTuiJian(); // 推荐购车
        $list['news'] = $this->indexNew(); // 新闻
        return json(['status' => 200, 'msg' => $list]);
    }
    
    /**
     * 活动（滚动字幕）
     * @return \think\response\Json
     */
    public function activity(){
        $activity = Db::table('up_activity')
            ->field('activity_id, activity_title')
            ->where('activity_type', 1)
            ->order('activity_time desc')
            ->select();
        return $activity;
//        if($activity){
//            return json(['status' => 200, 'msg' => $activity]);
//        }else{
//            return json(['status' => 200, 'msg' => []]);
//        }
    }
    
    /**
     * 活动详情
     * @return \think\response\Json
     * activity_id    活动ID
     */
    public function activityDetail(){
        header("Access-Control-Allow-Origin: *");
        $activity_id = input('activity_id');
        $info = Db::table('up_activity')
            ->field('activity_title, activity_content, activity_img, activity_time')
            ->where('activity_id', $activity_id)
            ->find();
        // 是否报名
        $have = Db::table('up_my_activity')
            ->where('ma_user_id', $this->user_id)
            ->where('ma_activity_id', $activity_id)
            ->find();
        if($have){
            $info['join'] = 1; // 已报名
        }else{
            $info['join'] = 2; // 未报名
        }
        return json(['status' => 200, 'msg' => $info]);
    }
    
    /**
     * 参加活动
     * @return \think\response\Json
     * activity_id    活动ID
     */
    public function joinActivity(){
        $activity_id = input('activity_id');
        $time = time();
        $end_time = Db::table('up_activity')->where('activity_id', $activity_id)->value('activity_end_time');
        $end = strtotime($end_time);
        if($time > $end) return json(['status' => 0, 'msg' => '活动已结束，不能参与']);
        $data = [
            'ma_user_id' => $this->user_id,
            'ma_activity_id' => $activity_id,
            'ma_time' => $this->create_time
        ];
        $res = Db::table('up_my_activity')->insert($data);
        if($res){
            return json(['status' => 200, 'msg' => '参加成功']);
        }else{
            return json(['status' => 0, 'msg' => '参加失败']);
        }
    }
    
    /**
     * 首页---推荐购车
     * @return \think\response\Json
     */
    public function carTuiJian(){
        $tuijian = Db::table('up_car')
            ->field('car_id, car_thumb')
            ->where('car_is_tuijian', 1)
            ->where('car_del', 1)
            ->order('car_time desc')
            ->select();
        return $tuijian;
//        if($tuijian){
//            return json(['status' => 200, 'msg' => $tuijian]);
//        }else{
//            return json(['status' => 200, 'msg' => []]);
//        }
    }
    
    /**
     * 首页---新闻
     * @return \think\response\Json
     */
    public function indexNew(){
        $news = Db::table('up_new')
            ->where('new_status', 1)
            ->field('new_id, new_title, new_second_title, new_content, new_type, new_img, new_link')
            ->limit(20)
            ->order('new_time desc')
            ->select();
        return $news;
//        if($news){
//            return json(['status' => 200, 'msg' => $news]);
//        }else{
//            return json(['status' => 200, 'msg' => []]);
//        }
    }
    
    /**
     * 新闻详情
     * @return \think\response\Json
     * new_id    新闻ID
     */
    public function newDetail(){
        $new_id = input('new_id');
        $detail = Db::table('up_new')
            ->where('new_id', $new_id)
            ->field('new_id, new_title, new_second_title, new_content, new_img')
            ->find();
        return json(['status' => 200, 'msg' => $detail]);
    }
    
    /**
     * 省列表
     * @return \think\response\Json
     */
    public function provinceList(){
        header("Access-Control-Allow-Origin: *");
        $list = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        return json(['status' => 200, 'msg' => $list]);
    }
    
    /**
     * 根据省ID，获取市列表
     * @return \think\response\Json
     * sheng_id    省ID
     */
    public function getCity(){
        header("Access-Control-Allow-Origin: *");
        $sheng_id = input('sheng_id');
        $list = Db::table('up_area')->where('pid', $sheng_id)->field('district_id, district')->select();
        return json(['status' => 200, 'msg' => $list]);
    }
    
    /**
     * 车辆分类
     * @return \think\response\Json
     */
    public function carCate(){
        header("Access-Control-Allow-Origin: *");
        $cate = Db::table('up_car_cate')->field('cc_id, cc_name')->select();
        return json(['status' => 200, 'msg' => $cate]);
    }
    
    /**
     * 根据分类获取车辆列表
     * @return \think\response\Json
     * car_cate_id    分类ID
     * page           页码
     */
    public function carListByCate(){
        header("Access-Control-Allow-Origin: *");
        $car_cate_id = input('car_cate_id');
        $carList = Db::table('up_car')
            ->join('up_car_cate', 'cc_id = car_cate_id', 'left')
            ->field('car_id, car_thumb, car_name, car_price, cc_name')
            ->where('car_del', 1)
            ->where('car_cate_id', $car_cate_id)
//            ->page($this->page, 10)
            ->order('car_time desc')
            ->select();
        if($carList){
            return json(['status' => 200, 'msg' => $carList]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 用户是否有查看车辆状态的权限
     * @return \think\response\Json
     */
    public function userRule(){
        $rule = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_is_allow_look');
        return json(['status' => 200, 'msg' => $rule]);
    }
}